import React, { useState, useEffect } from "react";
import "./App.css";
import ConfigTabs from "./components/ConfigTabs";
import StepItem from "./components/StepItem";
import { useStepConfigs } from "./hooks/useStepConfigs";
import { useElementPicker } from "./hooks/useElementPicker";
import { Step } from "./types";

function App() {
  const [loading, setLoading] = useState(false);
  const [editingTabId, setEditingTabId] = useState<string | null>(null);
  const [editingTabName, setEditingTabName] = useState<string>("");

  // 使用自定义 hooks
  const {
    configs,
    currentConfigId,
    steps,
    setSteps,
    loadConfigs,
    createNewConfig,
    switchConfig,
    deleteConfig,
    renameConfig,
  } = useStepConfigs();

  const { startElementPicker, getSelectedElement } = useElementPicker(setSteps);

  // 组件初始化
  useEffect(() => {
    loadConfigs();
  }, [loadConfigs]);

  // 标签编辑相关函数
  const startEditingTab = (configId: string, currentName: string) => {
    setEditingTabId(configId);
    setEditingTabName(currentName);
  };

  const finishEditingTab = async () => {
    if (!editingTabId || !editingTabName.trim()) {
      setEditingTabId(null);
      setEditingTabName("");
      return;
    }

    await renameConfig(editingTabId, editingTabName.trim());
    setEditingTabId(null);
    setEditingTabName("");
  };

  const cancelEditingTab = () => {
    setEditingTabId(null);
    setEditingTabName("");
  };

  // 添加新步骤
  const addStep = () => {
    const newStep: Step = {
      element: "",
      popover: {
        title: "新步骤",
        description: "请填写描述",
        side: "bottom",
        align: "start",
      },
      customStyles:
        ".driver-popover { \n  max-width: 100vw !important; \n}\n.driver-popover-description { \n  font-size: 12px !important; \n  word-break: keep-all !important; \n}",
    };
    setSteps([...steps, newStep]);
  };

  // 删除步骤
  const removeStep = (index: number) => {
    const newSteps = steps.filter((_, i) => i !== index);
    setSteps(newSteps);
  };

  // 更新步骤
  const updateStep = (index: number, field: string, value: string) => {
    const newSteps = [...steps];
    if (field === "element") {
      newSteps[index].element = value;
    } else if (field === "customStyles") {
      newSteps[index].customStyles = value;
    } else if (field.startsWith("popover.")) {
      const popoverField = field.replace("popover.", "");
      (newSteps[index].popover as any)[popoverField] = value;
    }
    setSteps(newSteps);
  };

  // 启动单个步骤引导
  const startSingleStep = async (step: Step, index: number) => {
    setLoading(true);
    try {
      const [tab] = await chrome.tabs.query({
        active: true,
        currentWindow: true,
      });
      if (tab.id) {
        // 如果元素选择器为空，尝试获取用户选中的元素
        let finalStep = { ...step };
        if (!step.element.trim()) {
          const selectedSelector = await getSelectedElement();
          if (selectedSelector) {
            finalStep.element = selectedSelector;
            // 同时更新步骤配置
            updateStep(index, "element", selectedSelector);
          } else {
            setLoading(false);
            return;
          }
        }

        chrome.tabs.sendMessage(tab.id, {
          action: "startCustomTour",
          data: [finalStep],
          customStyles: finalStep.customStyles,
        });

        // 关闭popup面板
        window.close();
      }
    } catch (error) {
      console.error("步骤启动失败:", error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="app">
      <div className="header">
        <h2>🚗 步骤引导配置</h2>

        <ConfigTabs
          configs={configs}
          currentConfigId={currentConfigId}
          editingTabId={editingTabId}
          editingTabName={editingTabName}
          onSwitchConfig={switchConfig}
          onStartEditingTab={startEditingTab}
          onFinishEditingTab={finishEditingTab}
          onCancelEditingTab={cancelEditingTab}
          onDeleteConfig={deleteConfig}
          onCreateNewConfig={createNewConfig}
          setEditingTabName={setEditingTabName}
        />
      </div>

      <div className="steps-container">
        {steps.map((step, index) => (
          <StepItem
            key={index}
            step={step}
            index={index}
            loading={loading}
            onRemoveStep={removeStep}
            onStartSingleStep={startSingleStep}
            onUpdateStep={updateStep}
            onStartElementPicker={startElementPicker}
          />
        ))}
      </div>

      <div className="bottom-actions">
        <button className="btn btn-add" onClick={addStep}>
          ➕ 添加步骤
        </button>
      </div>

      <div className="tips">
        <p>
          <strong>提示:</strong>{" "}
          可以手动填写元素选择器，或者在开发者工具中选择元素后直接点击"启动"按钮自动获取。
        </p>
        <p>
          <strong>使用方法:</strong> 1. 打开开发者工具(F12) → 2.
          选择Elements标签 → 3. 点击页面元素 → 4. 点击"启动"按钮
        </p>
      </div>
    </div>
  );
}

export default App;
